package cc.opcol.iot.app.web;

import cc.opcol.iot.app.auth.UserSessionService;
import cc.opcol.iot.app.vo.LoginForm;
import cc.opcol.iot.app.vo.OpcolError;
import cc.opcol.iot.app.vo.UserSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping(value = "/login")
public class loginController extends BaseController{

    @Autowired
    UserSessionService userSessionService;
    @RequestMapping(value = "",method = {RequestMethod.POST},consumes = "application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String login(@RequestBody String body, HttpServletResponse response) {
        LoginForm loginForm=getGson().fromJson(body,LoginForm.class);
        UserSession session=userSessionService.login(loginForm.getUsername(),loginForm.getPassword());
        ResourceVo resourceVo=new ResourceVo(session);
        if(session.isLogin()){
            Cookie cookie = new Cookie("accessKey", session.getAccessKey());
            cookie.setPath("/");
            response.addCookie(cookie);
        }else {
            resourceVo.setCode(OpcolError.AUTHENTICATION_FAILED);
        }
        return toJson(resourceVo);
    }
}
